# encoding: utf-8
""" 
@version: v1.0 
@author: autumner 
@license: Apache Licence  
@contact: 18322313385@163.com 
@site:  
@software: PyCharm 
@file: class_proxy1.py 
@time: 2019/6/25 11:36
"""
'''
类属性的代理访问
1.实现代理模式,使用环境：加入日志功能、只读访问等
'''

class Proxy:
    def __init__(self, obj):
        self._obj = obj

    # Delegate attribute lookup to internal obj(委托属性查找内部obj)
    def __getattr__(self, item):
        print('getattr:', item)
        return getattr(self._obj, item)

    # Delegate attribute assignment(代表属性赋值)
    def __setattr__(self, key, value):
        if key.startswith('_'):
            super().__setattr__(key, value)
        else:
            print('setattr:', key, value)
            setattr(self._obj, key, value)

    # Delegate attribute deletion(代表属性删除)
    def __delattr__(self, item):
        if item.startswith('_'):
            super().__delattr__(item)
        else:
            print('delattr:', item)
            delattr(self._obj, item)


# Example use
class Spam:
    def __init__(self, x):
        self.x = x

    def bar(self, y):
        print('Spam.bar:', self.x, y)


s = Spam(2)
p = Proxy(s)

print(p.x)
p.bar(3)
p.x = 37